package com.sdu.cloudservice.action;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.sdu.cloudservice.dao.AdminDao;
import com.sdu.cloudservice.dao.UserDao;
import com.sdu.cloudservice.dto.Envelope;
import com.sdu.cloudservice.entity.AdminEntity;
import com.sdu.cloudservice.entity.UserEntity;
import com.sdu.cloudservice.token.AdminToken;
import com.sdu.cloudservice.token.PassToken;
import com.sdu.cloudservice.token.UserToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * Create by zekdot on 19-7-2.
 */
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    UserDao userDao;
    @Autowired
    private AdminDao adminDao;
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token
        // 如果不是映射到方法直接通过
        if(!(object instanceof HandlerMethod)){
            return true;
        }
        httpServletRequest.setCharacterEncoding("UTF8");
        httpServletResponse.setCharacterEncoding("UTF8");
        HandlerMethod handlerMethod=(HandlerMethod)object;
        Method method=handlerMethod.getMethod();
        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        //检查有没有需要用户权限的注解
        if (method.isAnnotationPresent(UserToken.class)) {
            UserToken userToken = method.getAnnotation(UserToken.class);
            if (userToken.required()) {
                // 执行认证
                if (token == null) {
                    PrintWriter writer = httpServletResponse.getWriter();
                    writer.println(new Envelope(1024,"无token，请重新登录",null).toString());
                    writer.flush();
                    writer.close();
                    return false;
                    //                    throw new RuntimeException("无token，请重新登录");
                }
                // 如果是管理员
                if(!JWT.decode(token).getClaim("identity").asString().equals("admin")){
                    // 直接通过
                    return true;
                }
                // 获取 token 中的 user id
                String userId;
                try {
                    // 获取用户名
                    userId = JWT.decode(token).getAudience().get(0);
                } catch (JWTDecodeException j) {
                    throw new RuntimeException("401");
                }
                UserEntity user = userDao.findUserByUsername(userId);
                if (user == null) {
                    PrintWriter writer = httpServletResponse.getWriter();
                    writer.println(new Envelope(1022,"用户不存在，请重新登录",null).toString());
                    writer.flush();
                    writer.close();
                    return false;
                }
                // 验证 token
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
                try {
                    jwtVerifier.verify(token);
                } catch (JWTVerificationException e) {
                    throw new RuntimeException("401");
                }
                return true;
            }
        }
        // 检查有没有需要管理员权限的注解
        if (method.isAnnotationPresent(AdminToken.class)) {
            AdminToken userLoginToken = method.getAnnotation(AdminToken.class);
            if (userLoginToken.required()) {
                // 执行认证
                if (token == null) {
                    PrintWriter writer = httpServletResponse.getWriter();
                    writer.println(new Envelope(1021,"无token，请重新登录",null).toString());
                    writer.flush();
                    writer.close();
                    return false;
                    //                    throw new RuntimeException("无token，请重新登录");
                }
                if(!JWT.decode(token).getClaim("identity").asString().equals("admin")){
                    PrintWriter writer = httpServletResponse.getWriter();
                    writer.println(new Envelope(1020,"仅管理员可查看内容",null).toString());
                }
                // 获取 token 中的 user id
                String userId;
                try {
                    userId = JWT.decode(token).getAudience().get(0);
                } catch (JWTDecodeException j) {
                    throw new RuntimeException("401");
                }
                AdminEntity admin = adminDao.findAdminByUsername(userId);
                if (admin == null) {
                    PrintWriter writer = httpServletResponse.getWriter();
                    writer.println(new Envelope(1023,"管理员不存在，请重新登录",null).toString());
                    writer.flush();
                    writer.close();
                    return false;
                }
                // 验证 token
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(admin.getPassword())).build();
                try {
                    jwtVerifier.verify(token);
                } catch (JWTVerificationException e) {
                    throw new RuntimeException("401");
                }
                return true;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }
}
